//
//  PlayViewController.m
//  ProJectB_1
//
//  Created by lanou3g on 16/8/16.
//  Copyright © 2016年 yangshukai. All rights reserved.
//

#import "PlayViewController.h"

//屏幕宽
#define ScreenWidth     [[UIScreen mainScreen] bounds].size.width
//屏幕高
#define ScreenHeight    [[UIScreen mainScreen] bounds].size.height
//导航条高度
#define NavigationBarHeight     64.0


@interface PlayViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollVIew;

@property (nonatomic,strong)FootPlayView *footPlayView;

@property (nonatomic,strong)UIWebView *webView; // 详情

@property (nonatomic,strong)UIImageView *imageView; //

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSTimer *timer;

@property (nonatomic,strong)NSTimer *imageTimer;

@end

@implementation PlayViewController

static double angle = 0.0000;

- (void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"playDidFinish" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = [(DianTaiInfoModel*)_detailListArray[_selectPlay] title];
    _scrollVIew.delegate = self;
    _scrollVIew.contentSize = CGSizeMake(ScreenWidth*3, ScreenHeight);
    _scrollVIew.pagingEnabled = YES;
    _scrollVIew.bounces = NO;
    _scrollVIew.showsHorizontalScrollIndicator = NO;
    _scrollVIew.backgroundColor = [UIColor clearColor];
    [_scrollVIew setContentOffset:CGPointMake(ScreenWidth, 0)];
    _scrollVIew.backgroundColor = [UIColor flatMidNightColor];
    
    [self creatFootPlayView];
    [self creatWebView];
    [self creatImageView];
    [self creatListTableView];
    [self creatPlayManager];
    
    // 注册消息中心观察者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playFinish:) name:@"playDidFinish" object:nil];
    // 注册消息中心观察者用于关闭
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopPlayer:) name:@"stopPlayer" object:nil];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(back:)];
}
- (void)back:(UIBarButtonItem *)sender{
    [self.navigationController popViewControllerAnimated:YES];
    [_imageTimer invalidate];
    _imageTimer = nil;
    [_timer invalidate];
    _timer = nil;
}

- (void)playFinish:(NSNotification *)noti{
    // 刷新UI
    [self refreshUIUseIndex:[PlayerManager defaultManager].playIndex];
    NSString *str = [noti object];
    NSLog(@"%@",str);
}

- (void)stopPlayer:(NSNotification *)noti{
//    [[PlayerManager defaultManager] stop];
    NSLog(@"%@",[noti object]);
}

- (void)creatImageView{
    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth+30, NavigationBarHeight+110, ScreenHeight - NavigationBarHeight - 330, ScreenHeight - NavigationBarHeight - 330)];
    _imageView.layer.masksToBounds = YES;
    _imageView.layer.cornerRadius = (ScreenHeight - NavigationBarHeight - 320) / 2;
    
    NSString *url = _dianTaiInfoModel.playInfo.imgUrl;
    [_imageView sd_setImageWithURL:[NSURL URLWithString:url]];
    
    // 添加一个无限旋转的定时器
    _imageTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(xuanZhuan) userInfo:nil repeats:YES];
    
    [_scrollVIew addSubview:_imageView];
}
- (void)xuanZhuan{
    angle = angle + 0.002;//angle角度
    if (angle > 6.28) {//大于 M_PI*2(360度) 角度再次从0开始
        angle = 0;
    }
    CGAffineTransform transform = CGAffineTransformMakeRotation(angle);
    _imageView.transform = transform;
}

// web展示
- (void)creatWebView{
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(ScreenWidth*2, NavigationBarHeight, ScreenWidth, ScreenHeight - 110 - NavigationBarHeight)];
    
    _webView.backgroundColor = [UIColor clearColor];
    [_webView setOpaque:NO];
    // 详情的url
    NSString *url = _dianTaiInfoModel.playInfo.webview_url;
    // 将html进行第三方处理
    NSString *newString = [NSString importStyleWithHtmlString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:newString]];
    [_webView loadRequest:request];
    [_scrollVIew addSubview:_webView];
}
// 去掉网页背景
#warning !!!!!!!!!
//- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='transparent'"];
//    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'blue'"];
//}

- (void)creatFootPlayView{
    UIView *radioView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 110, ScreenWidth, 110)];
    radioView.backgroundColor = [UIColor clearColor];
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"FootPlayView" owner:nil options:nil];
    _footPlayView = views.lastObject;
    _footPlayView.backgroundColor = [UIColor clearColor];
    _footPlayView.frame = radioView.bounds;
    __weak typeof(self) weakSelf = self;
    _footPlayView.selectRadioBlock = ^(NSInteger index){
        [weakSelf refreshUIUseIndex:index];
    };
    [radioView addSubview:_footPlayView];
    [self.view addSubview:radioView];
}

- (void)creatListTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavigationBarHeight, ScreenWidth, ScreenHeight - 110 - NavigationBarHeight)];
    [_tableView registerNib:[UINib nibWithNibName:@"PlayTableViewCell" bundle:nil] forCellReuseIdentifier:@"PlayTableViewCell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    // 根据当前播放进行cell的选中设置
    NSIndexPath *index = [NSIndexPath indexPathForRow:_selectPlay inSection:0];
    [_tableView selectRowAtIndexPath:index animated:YES scrollPosition:(UITableViewScrollPositionNone)];
    [_tableView scrollToRowAtIndexPath:index atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
    [_scrollVIew addSubview:_tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _detailListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PlayTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"PlayTableViewCell" forIndexPath:indexPath];
    DianTaiInfoModel *model = _detailListArray[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];

    [cell setDataWith:model.playInfo];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self refreshUIUseIndex:indexPath.row];
    // 延迟0.1秒
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self changeAction:indexPath.row];
    });
}
- (void)changeAction:(NSInteger)index{
    // 改变当前播放单元
    PlayerManager *manager = [PlayerManager defaultManager];
    [manager changeMusicWithIndex:index];
}

- (void)creatPlayManager{
    // 播放器
    PlayerManager *manager = [PlayerManager defaultManager];
    // 当前要播放的index
    manager.playIndex = _selectPlay;
    // 播放列表
    [manager setMusicArray:_playListArray];
    // 播放
    [manager play];
    // 定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(playing) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

- (void)playing{
    // 改变slider位置和时间
    PlayerManager *manager = [PlayerManager defaultManager];
    // 设初值
    _footPlayView.slider.minimumValue = 0.01;
    _footPlayView.slider.maximumValue = manager.totalTime;
    _footPlayView.slider.value = manager.currentTime;
    // 时间显示
    _footPlayView.currentTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld",(int64_t)manager.currentTime/60,(int64_t)manager.currentTime%60];
    _footPlayView.totalTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld",(int64_t)manager.totalTime/60,(int64_t)manager.totalTime%60];
    // 时间走完 播放完成
    if (manager.currentTime >= manager.totalTime && manager.totalTime != 0) {
        [manager playDidFinish];
    }
}

// 根据位置改变数据
- (void)refreshUIUseIndex:(NSInteger)index{
    // 根据位置获取model
    _dianTaiInfoModel = _detailListArray[index];
    // webView
    NSString *urlStr = _dianTaiInfoModel.playInfo.webview_url;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [_webView loadRequest:request];
    // tableView
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_selectPlay inSection:0];
    // 取消选中状态
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 到当前位置
    indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionNone)];
    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
    // 改变选中cell颜色
    PlayTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    cell.markView.backgroundColor = [UIColor flatGreenSeaColor];
    // footPlayView
    [_footPlayView setPlayViewModel:_dianTaiInfoModel.playInfo];
    [_footPlayView.playButton setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    PlayerManager *manager = [PlayerManager defaultManager];
    manager.playState = PlayerStatePlay;
    _selectPlay = index;
    self.navigationItem.title = [(DianTaiInfoModel*)_detailListArray[_selectPlay] title];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
